package com.bestcem.xm.om.grpc.service;

import com.bestcem.xm.common.core.domain.web.RpcStatusResult;
import com.bestcem.xm.common.core.domain.web.ServiceResult;
import com.bestcem.xm.common.core.enums.ErrorCodeEnum;
import com.bestcem.xm.om.grpc.service.converter.IndustryConverter;
import com.bestcem.xm.om.grpc.v1.services.*;
import com.bestcem.xm.om.service.OmIndustryService;
import com.bestcem.xm.om.service.dto.SampleCodeDTO;
import com.bestcem.xm.user.constant.CommonConstant;
import io.grpc.stub.StreamObserver;
import lombok.extern.slf4j.Slf4j;
import net.devh.boot.grpc.server.service.GrpcService;
import org.apache.commons.lang3.StringUtils;

import javax.annotation.Resource;
import java.util.List;
import java.util.stream.Collectors;

/**
 * OmIndustryGrpcService
 *
 * @author zq.ding <zq.ding@idiaoyan.com>
 * @version v1.0
 * @date 2021/7/27 10:40
 */
@Slf4j
@GrpcService
public class OmIndustryGrpcService extends IndustryServiceGrpc.IndustryServiceImplBase {
    @Resource
    private OmIndustryService omIndustryService;

    /**
     * 创建Industry
     */
    @Override
    public void createIndustry(CreateIndustryRequest request, StreamObserver<CreateIndustryResponse> responseObserver) {
        CreateIndustryResponse.Builder builder = CreateIndustryResponse.newBuilder();
        Industry industry = request.getIndustry();
        ServiceResult<String> serviceResult = omIndustryService.insert(IndustryConverter.requestToParam(industry));
        // 返回数据
        if (serviceResult.isSuccess()) {
            builder.setId(serviceResult.getData());
            builder.setStatus(RpcStatusResult.success());
        } else {
            String errMsg = String.format(CommonConstant.ERROR_MSG_FORMATTER,
                    ErrorCodeEnum.SYSTEM_ERROR.getMsg(), serviceResult.getMsg());
            builder.setStatus(RpcStatusResult.error(errMsg));
        }
        responseObserver.onNext(builder.build());
        responseObserver.onCompleted();
    }

    /**
     * 更新Industry
     */
    @Override
    public void updateIndustry(UpdateIndustryRequest request, StreamObserver<UpdateIndustryResponse> responseObserver) {
        UpdateIndustryResponse.Builder builder = UpdateIndustryResponse.newBuilder();
        ServiceResult<String> serviceResult = omIndustryService
                .updateById(IndustryConverter.requestToParam(request.getIndustry()));
        // 返回数据
        if (serviceResult.isSuccess()) {
            builder.setId(serviceResult.getData());
            builder.setStatus(RpcStatusResult.success());
        } else {
            String errMsg = String.format(CommonConstant.ERROR_MSG_FORMATTER,
                    ErrorCodeEnum.SYSTEM_ERROR.getMsg(), serviceResult.getMsg());
            builder.setStatus(RpcStatusResult.error(errMsg));
        }
        responseObserver.onNext(builder.build());
        responseObserver.onCompleted();
    }

    /**
     * 批量删除Industry
     */
    @Override
    public void deleteIndustry(DeleteIndustryRequest request, StreamObserver<DeleteIndustryResponse> responseObserver) {
        DeleteIndustryResponse.Builder builder = DeleteIndustryResponse.newBuilder();
        String id = request.getId();
        ServiceResult<Integer> serviceResult = omIndustryService.deleteById(id);
        // 返回数据
        if (serviceResult.isSuccess()) {
            builder.setCount(serviceResult.getData());
            builder.setStatus(RpcStatusResult.success());
        } else {
            String errMsg = String.format(CommonConstant.ERROR_MSG_FORMATTER, ErrorCodeEnum.SYSTEM_ERROR.getMsg(), serviceResult.getMsg());
            builder.setStatus(RpcStatusResult.error(errMsg));
        }
        responseObserver.onNext(builder.build());
        responseObserver.onCompleted();
    }

    /**
     * 获取单个Industry
     */
    @Override
    public void getIndustry(GetIndustryRequest request, StreamObserver<GetIndustryResponse> responseObserver) {
        GetIndustryResponse.Builder builder = GetIndustryResponse.newBuilder();
        ServiceResult<Industry> serviceResult = omIndustryService.findById(request.getId());
        // 返回数据
        if (serviceResult.isSuccess()) {
            builder.setIndustry(serviceResult.getData());
            builder.setStatus(RpcStatusResult.success());
        } else {
            String errMsg = String.format(CommonConstant.ERROR_MSG_FORMATTER, ErrorCodeEnum.SYSTEM_ERROR.getMsg(), serviceResult.getMsg());
            builder.setStatus(RpcStatusResult.error(errMsg));
        }
        responseObserver.onNext(builder.build());
        responseObserver.onCompleted();
    }

    /**
     * 通过id批量获取Industry
     */
    @Override
    public void listIndustriesByIds(ListIndustriesByIdsRequest request, StreamObserver<ListIndustriesByIdsResponse> responseObserver) {
        ListIndustriesByIdsResponse.Builder builder = ListIndustriesByIdsResponse.newBuilder();
        ServiceResult<List<Industry>> serviceResult = omIndustryService.selectByIds(request.getIdsList());
        // 返回数据
        if (serviceResult.isSuccess()) {
            builder.addAllIndustries(serviceResult.getData());
            builder.setStatus(RpcStatusResult.success());
        } else {
            String errMsg = String.format(CommonConstant.ERROR_MSG_FORMATTER, ErrorCodeEnum.SYSTEM_ERROR.getMsg(), serviceResult.getMsg());
            builder.setStatus(RpcStatusResult.error(errMsg));
        }
        responseObserver.onNext(builder.build());
        responseObserver.onCompleted();
    }

    /**
     * 通过区域、行业id或行业code查询行业信息、对应区域的销售电话
     */
    @Override
    public void getIndustryContact(GetIndustryContactRequest request, StreamObserver<GetIndustryContactResponse> responseObserver) {
        GetIndustryContactResponse.Builder builder = GetIndustryContactResponse.newBuilder();
        ServiceResult<GetIndustryContactResponse> serviceResult = omIndustryService.findByDistrictAndIdOrCode(request.getDistrict(), request.getId(), request.getCode());
        // 返回数据
        if (serviceResult.isSuccess()) {
            builder.addAllPhones(serviceResult.getData().getPhonesList());
            builder.setIndustry(serviceResult.getData().getIndustry());
            builder.addAllEmails(serviceResult.getData().getEmailsList());
            builder.setStatus(RpcStatusResult.success());
        } else {
            String errMsg = String.format(CommonConstant.ERROR_MSG_FORMATTER, ErrorCodeEnum.SYSTEM_ERROR.getMsg(), serviceResult.getMsg());
            builder.setStatus(RpcStatusResult.error(errMsg));
        }
        responseObserver.onNext(builder.build());
        responseObserver.onCompleted();
    }

    /**
     * 获取行业信息
     */
    @Override
    public void getUserIndustryInfo(GetUserIndustryInfoRequest request, StreamObserver<GetUserIndustryInfoResponse> responseObserver) {
        GetUserIndustryInfoResponse.Builder builder = GetUserIndustryInfoResponse.newBuilder();
        ServiceResult<IndustryInfo> serviceResult = omIndustryService.findByCodeOrRouteOrIp(request.getCode(), request.getRoute(), request.getIp());
        // 返回数据
        if (serviceResult.isSuccess()) {
            builder.setInfo(serviceResult.getData());
            builder.setStatus(RpcStatusResult.success());
        } else {
            String errMsg = String.format(CommonConstant.ERROR_MSG_FORMATTER, ErrorCodeEnum.SYSTEM_ERROR.getMsg(), serviceResult.getMsg());
            builder.setStatus(RpcStatusResult.error(errMsg));
        }
        responseObserver.onNext(builder.build());
        responseObserver.onCompleted();
    }

    /**
     * <pre>
     * 通过查询条件批量一次性获取所有符合条件的Industry
     * </pre>
     */
    @Override
    public void listIndustries(ListIndustriesRequest request, StreamObserver<ListIndustriesResponse> responseObserver) {
        ListIndustriesResponse.Builder builder = ListIndustriesResponse.newBuilder();

        Integer code = null;
        if (StringUtils.isNotEmpty(request.getCode())) {
            code = Integer.parseInt(request.getCode());
        }
        Integer order = null;
        if (StringUtils.isNotEmpty(request.getOrder())) {
            order = Integer.parseInt(request.getOrder());
        }
        ServiceResult<List<Industry>> serviceResult = omIndustryService.listIndustries(request.getId(),
                code, request.getName(), order);
        // 返回数据
        if (serviceResult.isSuccess()) {
            builder.addAllIndustries(serviceResult.getData());
            builder.setStatus(RpcStatusResult.success());
        } else {
            String errMsg = String.format(CommonConstant.ERROR_MSG_FORMATTER, ErrorCodeEnum.SYSTEM_ERROR.getMsg(), serviceResult.getMsg());
            builder.setStatus(RpcStatusResult.error(errMsg));
        }
        responseObserver.onNext(builder.build());
        responseObserver.onCompleted();
    }

    @Override
    public void listIndustrySampleCodes(ListIndustrySampleCodesRequest request,
                                       StreamObserver<ListIndustrySampleCodesResponse> responseObserver) {
        ServiceResult<List<SampleCodeDTO>> serviceResult = omIndustryService.listIndustrySampleCode();

        ListIndustrySampleCodesResponse.Builder builder = ListIndustrySampleCodesResponse.newBuilder();
        // 返回数据
        if (serviceResult.isSuccess()) {
            List<SampleCode> list = serviceResult.getData().stream().map(o ->
                    SampleCode.newBuilder().setOrgCode(o.getOrgCode()).setOrgId(o.getOrgId()).build()
            ).collect(Collectors.toList());
            builder.addAllCodes(list);
            builder.setStatus(RpcStatusResult.success());
        } else {
            String errMsg = String.format(CommonConstant.ERROR_MSG_FORMATTER, ErrorCodeEnum.SYSTEM_ERROR.getMsg(), serviceResult.getMsg());
            builder.setStatus(RpcStatusResult.error(errMsg));
        }
        responseObserver.onNext(builder.build());
        responseObserver.onCompleted();
    }
}
